﻿using BookManege.entity;
using BookManege.service;
using Org.BouncyCastle.Utilities;

namespace BookManege.controller
{
    public partial class bookManege : Form
    {
        private BookManegeService bookManegeService;
        private int pageNum;
        private int pageSize;
        private MyHttpRespons MyHttpRespons;
        private Dictionary<string, Bitmap> imageCache = new Dictionary<string, Bitmap>();
        public bookManege()
        {
            this.bookManegeService = new BookManegeService();
            InitializeComponent();
            this.pageNum = 1;
            this.pageSize = 10;
            this.MyHttpRespons = new MyHttpRespons();
        }

        private void bookManege_Load(object sender, EventArgs e)
        {
            GetBookList();
            if (pageNum == 1)
            {
                linkLabel1.Enabled = false;
            }
            if (bookManegeService.GetCount() - pageNum * pageSize < 0)
            {
                linkLabel2.Enabled = false;
            }
            textBox3.Text = pageNum.ToString();
        }
        public void GetBookList()
        {
            dataGridView1.RowTemplate.Height = 100;
            dataGridView1.DataSource = bookManegeService.GetBookList(pageNum, pageSize);
            LoadImagesAsync();
        }
        public  void LoadImagesAsync()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow row = dataGridView1.Rows[i];
                string imageUrl = row.Cells["封面链接"].Value as string;
                Bitmap resultImg = null;
                if (!string.IsNullOrEmpty(imageUrl))
                {
                    //查看缓存有没有
                    if(imageCache.TryGetValue(imageUrl,out Bitmap bitmap1))
                    {
                        resultImg = bitmap1;
                    }
                    else
                    {
                        try
                        {
                            using Image image = Image.FromFile(Program.bookPath + imageUrl + ".jpg");
                            //重新绘制一下图片，图片太鸡儿大了
                            int newHeight = 90;
                            float originalAspectRatio = (float)image.Width / image.Height;
                            int newWidth = (int)(newHeight * originalAspectRatio);
                            resultImg = new Bitmap(newWidth, newHeight);
                            using (Graphics graphics = Graphics.FromImage(resultImg))
                            {
                                // 设置高质量插值法  
                                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                // 绘制原始图像到新创建的Bitmap上  
                                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
                            }
                            //加入缓存
                            imageCache.Add(imageUrl, resultImg);
                        }catch(Exception ex)
                        {
                            continue;
                        }
                    }
                   dataGridView1.Invoke((MethodInvoker)delegate{row.Cells["封面"].Value = resultImg;});
                }
            }
        }
        //删除修改
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "删除")
            {
                if (MessageBox.Show("确认要删除《" + dataGridView1.Rows[e.RowIndex].Cells["书名"].Value.ToString() + "》吗", "确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    MessageBox.Show(bookManegeService.DeleteById(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString()) > 0 ? "删除成功!" : "删除失败!");
                }
                GetBookList();
                LoadImagesAsync();
            }
            else if (dataGridView1.Columns[e.ColumnIndex].Name == "修改")
            {
                DataGridViewRow data = dataGridView1.Rows[e.RowIndex];
                //Decimal转换为Double必须用Convert.ToDouble保持精度和安全转换
                Book book = new((long)data.Cells["id"].Value, data.Cells["书名"].Value.ToString(), data.Cells["封面链接"].Value.ToString(),data.Cells["作者"].Value.ToString(),
                    data.Cells["ICBN"].Value.ToString(), Convert.ToDouble(data.Cells["价格"].Value),Convert.ToInt32(data.Cells["状态"].Value), Convert.ToInt32(data.Cells["数量"].Value), DateTime.Parse(data.Cells["加入日期"].Value.ToString()));
                MessageBox.Show(bookManegeService.Update(book) > 0 ? "更新成功!" : "更新失败!");
                GetBookList();
                LoadImagesAsync();
            }
        }
        public int GetCount()
        {
            return bookManegeService.GetCount();
        }
        //重置按钮
        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.Text = textBox1.Text = comboBox1.Text = dateTimePicker1.Text = dateTimePicker2.Text = "";
            GetBookList();
        }
        //搜索按钮
        private void button1_Click(object sender, EventArgs e)
        {
            string bookName = textBox1.Text;
            string bookAuther = textBox2.Text;
            string iCBN = textBox4.Text;
            DateTime startDate = DateTime.Parse(dateTimePicker1.Text);
            DateTime endDate = DateTime.Parse(dateTimePicker2.Text);
            dataGridView1.DataSource = bookManegeService.search(bookName, bookAuther, iCBN,startDate, endDate);
            LoadImagesAsync();
        }
        //上一页
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (pageNum == 1)
            {
                linkLabel1.Enabled = false;
            }
            else
            {
                linkLabel2.Enabled = true;
                --pageNum;
                textBox3.Text = pageNum.ToString();
                GetBookList();
                LoadImagesAsync();
            }
        }
        //下一页
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (bookManegeService.GetCount() - pageNum * pageSize < 0)
            {
                linkLabel2.Enabled = false;
            }
            else
            {
                linkLabel1.Enabled = true;
                ++pageNum;
                textBox3.Text = pageNum.ToString();
                GetBookList();
                LoadImagesAsync();
            }
        }
        //显示行数下拉框
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            pageNum = 1;
            pageSize = (comboBox2.SelectedIndex + 1) * 10;
            GetBookList();
            LoadImagesAsync();
        }
        //页码跳转
        private void button3_Click(object sender, EventArgs e)
        {
            pageNum = int.Parse(textBox3.Text);
            GetBookList();
            LoadImagesAsync();
        }
        //录入ICBN
        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show("啊哈");
        }
    }
}
